"""
Author： Mr.Sun
Datetime： 2023/3/24 18:51 
FileName: grpc_params.py
Desc: 
"""
import json
from grpc_requests import Client

protobuf_type_enum = {
    'TYPE_DOUBLE': 1,
    'TYPE_FLOAT': 2,
    'TYPE_INT64': 3,
    'TYPE_UINT64': 4,
    'TYPE_INT32': 5,
    'TYPE_FIXED64': 6,
    'TYPE_FIXED32': 7,
    'TYPE_BOOL': 8,
    'TYPE_STRING': 9,
    'TYPE_GROUP': 10,
    'TYPE_MESSAGE': 11,
    'TYPE_BYTES': 12,
    'TYPE_UINT32': 13,
    'TYPE_ENUM': 14,
    'TYPE_SFIXED32': 15,
    'TYPE_SFIXED64': 16,
    'TYPE_SINT32': 17,
}


def grpc_information(reflection_url):
    client = Client.get_by_endpoint(reflection_url)
    service_list = list(client.service_names)
    services_result = []
    # 删除不需要的服务
    service_list.remove('grpc.reflection.v1alpha.ServerReflection')
    service_list.remove('grpc.reflection.v1.ServerReflection')

    for service in service_list:
        # 获取所有的服务
        service_descriptor = client.get_service_descriptor(service)
        # 获取服务下面的方法
        method_list = [x.name for x in service_descriptor.methods]
        methods_result = []
        for method in method_list:
            # 获取方法的描述
            method_descriptor = client.get_method_descriptor(service, method)
            params_list = [
                {"name": x.camelcase_name,
                 "type": [k.replace('TYPE_', '').lower() for k, v in protobuf_type_enum.items() if v == x.type][0]
                 } for
                x in method_descriptor.input_type.fields]
            result = {method: params_list}
            methods_result.append(result)
        services_result.append({service: methods_result})
    return json.dumps(services_result, ensure_ascii=False, indent=2)


if __name__ == '__main__':
    print(grpc_information('112.124.46.38:20001'))
